package com.library.controller;

import com.library.entity.Admin;
import com.library.entity.Book;
import com.library.entity.Borrow;
import com.library.entity.Reader;
import com.library.service.BookService;
import com.library.service.LoginService;
import com.library.service.impl.BookServiceImpl;
import com.library.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private LoginService loginService = new LoginServiceImpl();
    private BookService bookService = new BookServiceImpl();

    /**
     * 完成登陆模块
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取登录名和密码
        String userName = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");
        Object user = loginService.login(userName, password, type);
        HttpSession session = req.getSession();
        if (user != null) {
            switch (type) {
                case "reader":
                    Reader reader = (Reader) user;
                    session.setAttribute("reader", reader);
                    resp.sendRedirect("/book?page=1");
                    break;
                case "admin":
                    Admin admin = (Admin) user;
                    session.setAttribute("admin", admin);
                    //获取所有待审核的数据
                    resp.sendRedirect("/admin?method=findAllBorrow&page=1");
                    break;
            }
        } else {
            System.out.println("fail");
        }
    }
}
